package com.yimi.yinhepda.db.helper;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.misc.JavaxPersistenceImpl;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTable;
import com.j256.ormlite.table.TableUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 文 件 名:  DatabaseUtil.java
 * 版    权:  cttq
 * 描    述:  <数据库升级操作类>
 * 版    本： <版本号>
 * 创 建 人:  cam
 * 创建时间:  2016年6月21日
 *
 * @author 000432
 */
public class DatabaseUtil {
  /**
   * TAG
   */
  public static final String TAG = DatabaseUtil.class.getSimpleName();

  /**
   * 数据库表操作类型
   * ADD 表新增字段
   * DELETE 表删除字段
   */
  public enum OperationType {
    ADD, DELETE
  }

  /**
   * <升级表，增加字段>
   * <功能详细描述>
   *
   * @param db the db
   * @param cs the cs
   * @param clazz the clazz
   * @param type 返回类型:void
   */
  public static void upgradeTable(SQLiteDatabase db, ConnectionSource cs, Class<?> clazz, OperationType type) {
    String tableName = extractTableName(clazz);

    db.beginTransaction();
    try {

      // Rename table
      String tempTableName = tableName + "_temp";
      String sql = "ALTER TABLE " + tableName + " RENAME TO " + tempTableName;
      db.execSQL(sql);

      // Create table
      try {
        sql = TableUtils.getCreateTableStatements(cs, clazz).get(0).toString();
        db.execSQL(sql);
      } catch (Exception e) {
        e.printStackTrace();
        TableUtils.createTable(cs, clazz);
      }

      // Load data
      String columns;
      if (type == OperationType.ADD) {
        columns = Arrays.toString(getColumnNames(db, tempTableName)).replace("[", "").replace("]", "");
      } else if (type == OperationType.DELETE) {
        columns = Arrays.toString(getColumnNames(db, tableName)).replace("[", "").replace("]", "");
      } else {
        throw new IllegalArgumentException();
      }
      sql = "INSERT INTO " + tableName + "(" + columns + ")" + " SELECT " + columns + " FROM " + tempTableName;
      db.execSQL(sql);

      // Drop temp table
      sql = "DROP TABLE IF EXISTS " + tempTableName;
      db.execSQL(sql);

      db.setTransactionSuccessful();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      db.endTransaction();
    }
  }

  /**
   * <获取表名(ormlite DatabaseTableConfig.java)>
   * <功能详细描述>
   *
   * @return 返回类型:String
   */
  private static String extractTableName(Class<?> clazz) {
    DatabaseTable databaseTable = (DatabaseTable) clazz.getAnnotation(DatabaseTable.class);
    String name;
    if (databaseTable != null && databaseTable.tableName() != null && databaseTable.tableName().length() > 0) {
      name = databaseTable.tableName();
    } else {
            /*
             * NOTE: to remove javax.persistence usage, comment the following
             * line out
             */
      //            name = JavaxPersistence.getEntityName(clazz);

      name = new JavaxPersistenceImpl().getEntityName(clazz);
      if (name == null) {
        // if the name isn't specified, it is the class name lowercased
        name = clazz.getSimpleName().toLowerCase();
      }
    }
    return name;
  }

  /**
   * <获取表的列名>
   * <功能详细描述>
   *
   * @return 返回类型:String[]
   */
  private static String[] getColumnNames(SQLiteDatabase db, String tableName) {

    Cursor cursor = null;
    List<String> columnNames = new ArrayList<String>();
    try {
      cursor = db.rawQuery("PRAGMA table_info(" + tableName + ")", null);

      if (cursor.moveToFirst()) {
        do {
          columnNames.add(cursor.getString(cursor.getColumnIndexOrThrow("name")));
        } while (cursor.moveToNext());
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (cursor != null) {
        cursor.close();
      }
    }
    return columnNames.toArray(new String[] {});
  }
}